<?php
/**
 * Created by PhpStorm.
 * User: bg
 * Date: 2017/9/27 0027
 * Time: 上午 9:15
 */
namespace app\api\controller;

use think\Exception;
use think\Request;
use think\Validate;
use think\Db;
use think\controller\Rest;
use app\common\model\WorkOrder;
use app\common\model\Engineers;
use app\common\model\Customer;
use app\common\model\Parts;
//工程人员工单
class Eworkorder extends RestUserBase{

    protected $workorderDao;
    protected $engineersDao;
    protected $customerDao;
    protected $partsDao;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->workorderDao =  new WorkOrder();
        $this->engineersDao =  new Engineers();
        $this->customerDao =  new Customer();
        $this->partsDao =  new Parts();
    }

    //工单列表
    public function listorder(){
        $work_order_status = config('work_order_status');
        $workorder_type = config('workorder_type');
        $status =  trim(input('status'));
        $bid =  trim(input('bid'));
        if(!array_key_exists($status,$work_order_status)){
            $this->error('非法数据');
        }
        if(!array_key_exists($bid,$workorder_type)){
            $this->error('非法数据');
        }
        $jobtype = $workorder_type[$bid];
        $page = input('page')?input('page'):1;
        $limits = config('pagesize');
        $where['business_id'] = $bid;
        $where['b.repair_id'] = $this->userId;
        $where['work_order_status'] = $status;
        $where['b.is_delete'] = 0;
        $datalist = $this->workorderDao->getAllByWhere($where,$page,$limits);
        $groupCount = $this->workorderDao->field('business_id,count(work_order_id) as value')->where(array('repair_id'=>$this->userId,'work_order_status'=>7))->group('business_id')->select();

        $groupBusiness = array(
            array('business_id'=>1,'value'=>0),
            array('business_id'=>2,'value'=>0),
            array('business_id'=>3,'value'=>0),
            array('business_id'=>4,'value'=>0),
            array('business_id'=>5,'value'=>0),
            array('business_id'=>6,'value'=>0),
            array('business_id'=>7,'value'=>0),
            array('business_id'=>8,'value'=>0),
        );
        foreach ($groupCount as $key=>$val){
            $business_id = $val['business_id'];
            $retv = array_filter($groupBusiness, function($t) use ($business_id) { return $t['business_id'] == $business_id; });
            foreach ($retv as $key=>$v){
                $groupBusiness[$key]['value'] = $val['value'];
            }
        }

        if(!$datalist){
            $msg['code'] = -1;
            $msg['msg'] = '没有更多数据了';
            $data['groupCount'] = $groupBusiness;
            $this->error($msg,$data);
        }
        foreach ($datalist as $key=>&$val){
            $val['jobtype'] = $jobtype;
        }
        $ret['groupCount'] = $groupBusiness;
        $ret['list'] = $datalist;
        $this->success('成功',$ret);
    }

    //接单
    public function taking(){
        $validate = new Validate([
            'woid' => 'require',
        ]);
        $validate->message([
            'woid.require' => '缺少工单ID',
        ]);
        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $work_order_id = trim($data['woid']);
        $where['work_order_id'] = $work_order_id;
        $where['is_delete'] = 0;
        $woinfo = $this->workorderDao->where($where)->find();
        if(!$woinfo){
            $this->error('工单数据错误');
        }
        $updata['work_order_status'] = 8;
        $eid=$woinfo['repair_id'];
        $eTemp=db('engineers')->where(array('engineers_id'=>$eid))->find();
        $str='【工程人员】'.$eTemp['engineers_name'].' 接单成功';
        $lData=[
            'work_order_id'=>$work_order_id,
            'create_work_time'=>0,
            'operating_time'=>time(),
            'e_id'=>$eid,
            'operating_type'=>2,
            'operating_status'=>8,
            'remarks'=>$str
        ];
        $ret = $this->workorderDao->where($where)->update($updata);
        if($ret){
            //接单日志
            db('work_order_log')->insert($lData);
            $this->success('接单成功');
        }else{
            $this->error('接单失败');
        }
    }

    //工单详情
    public function getorderinfo(){
        $woid = input('woid');
        $orderinfo = $this->workorderDao->getDetails($woid);
        if(!$orderinfo){
            $this->error('异常');
        }
        $pTypeList = $this->partsDao->getAllType();
        foreach ($pTypeList as $key=>&$val){
            $val['mparts'] =  $this->partsDao->queryparts($val['id'],'parts_id,parts_name');
        }
        $orderinfo['partsType'] = $pTypeList;
        $this->success('成功',$orderinfo);
    }

    //根据分类ID查询配件
    public function queryparts(){
        $validate = new Validate([
            'tid' => 'require',
        ]);
        $validate->message([
            'tid.require' => '缺少分类ID',
        ]);
        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $typeList = $this->partsDao->queryparts($data['tid']);
        if(!$typeList){
            $this->error('没有数据');
        }
        $this->success('成功',$typeList);
    }

    //处理工单
    public function handleOrder(){
        $validate = new Validate([
            'woid' => 'require',
        ]);
        $validate->message([
            'woid.require' => '缺少参数',
        ]);
        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $woid = $data['woid'];
        $gWhere['work_order_id'] = $woid;
        $gWhere['work_order_status'] = 8;
        $gWhere['is_delete'] = 0;
        $workOrderInfo = $this->workorderDao->getOne($gWhere);
        if(!$workOrderInfo){
            $this->error('数据异常');
        }
        Db::startTrans();
        try{
            $parts = isset($data['parts'])?$data['parts']:false;
            if($parts){
               $parts = json_decode($parts,true);
               foreach ($parts as $key=>$val){
                   $idata['work_order_id'] = $woid;
                   $idata['parts_id'] = $key;
                   $idata['parts_number'] = (int)$val;
                   db('work_parts')->insert($idata);
               }
            }
            $uData['engineers_remarks'] = $data['remarks'];
            $uData['work_order_status'] = 9;
            $uWhere['work_order_id'] = $woid;            
            $wOrder=$this->workorderDao->getOne($uWhere);
            $eData=db('engineers')->where(array('engineers_id'=>$wOrder['repair_id']))->find();
            $rData=[
                'username'=>$eData['engineers_name'],
                'operating_time'=>time(),
                'work_order_id'=>$woid,
                'remarks'=>$data['remarks']
            ];
            $res=db('work_order_remarks')->insert($rData);
            //日志
            $str='【工程人员】'.$eData['engineers_name'].' 完成工单';
            $lData=[
                'work_order_id'=>$woid,
                'create_work_time'=>0,
                'operating_time'=>time(),
                'e_id'=>$wOrder['repair_id'],
                'operating_type'=>2,
                'operating_status'=>9,
                'remarks'=>$str
            ];
            $this->workorderDao->edit($uWhere,$uData);
            db('work_order_log')->insert($lData);
            Db::commit();
            $this->success('处理成功');
        }catch (Exception $e){
            Db::rollback();
            $this->success('处理失败',$e);
        }

    }


}